<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getRoleList, getUserList } from '../request/api'
import type { User, Role, PageParams, PageResponse } from '../type'

// 表格列定义接口
interface TableColumn {
  label: string;
  prop: string;
  width?: number | string;
  fixed?: string;
  formatter?: (row: any, column: any) => string;
}

// 标签页状态
const activeTab = ref('first')

// 用户列表相关状态
const userList = ref<User[]>([])
const userTotal = ref(0)
const loading = ref(false)

// 查询参数
const queryParams = ref<PageParams>({
  pageNum: 1,
  pageSize: 10,
  username: '',
  status: undefined
})

// 角色列表相关状态
const roleList = ref<Role[]>([])
const roleLoading = ref(false)

// 表格列定义
const userColumns: TableColumn[] = [
  { label: '用户ID', prop: 'id', width: 80 },
  { label: '用户名', prop: 'username' },
  { label: '昵称', prop: 'nickname' },
  { label: '邮箱', prop: 'email' },
  { label: '手机号', prop: 'phone' },
  { 
    label: '状态', 
    prop: 'status',
    formatter: (row: User) => {
      return row.status === 1 ? '启用' : '禁用'
    }
  },
  { label: '创建时间', prop: 'createTime' },
  { 
    label: '操作', 
    prop: 'action',
    width: 150,
    fixed: 'right'
  }
]

const roleColumns: TableColumn[] = [
  { label: '角色ID', prop: 'id', width: 80 },
  { label: '角色名称', prop: 'name' },
  { label: '角色描述', prop: 'description' },
  { label: '创建时间', prop: 'createTime' },
  { 
    label: '操作', 
    prop: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await getUserList(queryParams.value) as PageResponse<User>
    if (res.code === 200) {
      userList.value = res.data.list
      userTotal.value = res.data.count
    } else {
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  roleLoading.value = true
  try {
    const res = await getRoleList() as PageResponse<Role>
    if (res.code === 200) {
      roleList.value = res.data.list
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error(error)
  } finally {
    roleLoading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  queryParams.value.pageNum = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    username: '',
    status: undefined
  }
  fetchUserList()
}

// 分页处理
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  fetchUserList()
}

const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  fetchUserList()
}

// 标签页切换时加载对应数据
const handleTabChange = (tab: string) => {
  if (tab === 'second' && roleList.value.length === 0) {
    fetchRoleList()
  }
}

// 初始加载
onMounted(() => {
  fetchUserList()
})
</script>

<template>
  <div class="users-container">
    <el-tabs 
      v-model="activeTab" 
      type="border-card"
      @tab-change="handleTabChange"
    >
      <!-- 用户列表 -->
      <el-tab-pane label="用户列表" name="first">
        <div class="search-bar">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名或昵称"
            style="width: 300px; margin-right: 10px"
          />
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            style="width: 150px; margin-right: 10px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
        
        <el-table
          v-loading="loading"
          :data="userList"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            v-for="column in userColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :fixed="column.fixed"
            :formatter="column.formatter"
          >
            <template #default="{ row }" v-if="column.prop === 'action'">
              <el-button size="small" type="primary" style="margin-right: 5px">编辑</el-button>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      
      <!-- 角色列表 -->
      <el-tab-pane label="角色列表" name="second">
        <div class="role-list">
          <el-table
              v-loading="roleLoading"
              :data="roleList"
              style="width: 100%"
            >
              <el-table-column
                v-for="column in roleColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                :fixed="column.fixed"
              >
                <template #default="{ row }" v-if="column.prop === 'action'">
                  <el-button size="small" type="primary" style="margin-right: 5px">编辑</el-button>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
}

.search-bar {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-list {
  margin-top: 20px;
}
</style>